#include "ota_memchunk.h"
#include <stdlib.h>
#include <string.h>

Memchunk *ota_memchunk_init()
{
    Memchunk *memchunk = (Memchunk *)malloc(sizeof(Memchunk));
    if (!memchunk)
    {
        goto CHUNK_MALLOC_FAILED;
    }
    memchunk->data = malloc(1);
    if (!memchunk->data)
    {
        goto DATA_MALLOC_FAILED;
    }
    memchunk->size = 0;
    memset(memchunk->data, 0, 1);

    return memchunk;
DATA_MALLOC_FAILED:
    free(memchunk);
CHUNK_MALLOC_FAILED:
    return NULL;
}

int ota_memchunk_append(Memchunk *memchunk, const void *data, size_t len)
{
    void *tmp = realloc(memchunk->data, memchunk->size + len + 1);
    if (!tmp)
    {
        return -1;
    }
    memchunk->data = tmp;
    memcpy(memchunk->data + memchunk->size, data, len);
    memchunk->size += len;
    memset(memchunk->data + memchunk->size, 0, 1);
    return 0;
}

void ota_memchunk_free(Memchunk *memchunk)
{
    free(memchunk->data);
    free(memchunk);
}
